package hit.edu.zjc.Tool;

import java.io.*;
import java.util.*;

public class RWObject
{
	private RWObject(){}//防止被创建
	private static ObjectOutputStream out=null;
	private static ObjectInputStream in=null;

	
	public static void WriteObject(Object obj, String pos)
	{
		try
		{
		out=new ObjectOutputStream( new FileOutputStream(pos,false));
		out.writeObject(obj);
      out.flush();
      out.close();
      out=null;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public static Object ReadByteObject(String pos)
	{
		File file=new File(pos);
    	if(!file.exists())
    	{
    		 	return null;
    	}
    	try 
    	{
	    		byte[] byteobj=ObjectConvert.input2byte(new FileInputStream(pos));
	    		Object obj=ObjectConvert.ByteArrayToObject(byteobj);
	    		return obj;
    	}
    	catch (Exception e) 
    	{
    			e.printStackTrace();
    			return null;
    	}
	}
	
	public static Object ReadObject(String pos)
	{
    	File file=new File(pos);
    	if(!file.exists())
    	{
    		 	return null;
    	}
    	try {
    			in = new ObjectInputStream(new FileInputStream(pos));
    			Object obj  = in.readObject();
    			in.close();
    			in = null;
    			return obj;
    		}
    	catch (Exception e) {
    			e.printStackTrace();
    			return null;
    		}
	}
	
   public static void WriteObjects(Object[] obj ,String pos) 
    {
	 try{
	 	ArrayList<Object> array=new ArrayList<Object>();
	 	for(int i=0;i<obj.length;i++)
	 	    array.add(obj[i]);
	     out=null;
	     System.gc();
          out=new ObjectOutputStream( new FileOutputStream(pos,false));
             out.writeObject(array);
             out.flush();
             out.close();
             out=null;
             System.gc();
          }
       catch(Exception e)
        {
	            System.out.println(e);
	   }
    }

    public static Object[] ReadObjects(String pos) 
    { 
    	ArrayList<Object> b2=null;
    	Object a=null;
    	File file=new File(pos);
    	if(!file.exists())
    	{
    		   Object[] none=new Object[0];
    		 	return none;
    		}
    
    	try {
    			in = null;
    			System.gc();
    			in = new ObjectInputStream(new FileInputStream(pos));
 
    			a  = in.readObject();
 
    			in.close();
    			in = null;
    			System.gc();
    		}
    	catch (Exception e) {
    			System.out.println(e);
    		}
    	b2=(ArrayList<Object>)a;
    	return b2.toArray();
    }
}

